/*
 * Copyright (C) 2018 - 2019, Jue Huang <rabbit@pear.hk>
 *
 * KeyFile Format:
 * {
 *     "address":  "",
 *     "pub_key":  {
 *         "type": "",
 *         "pub": ""
 *     },
 *     "priv_key": {
 *         "type": "",
 *         "priv": ""
 *     }
 * }
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "pear_key.h"
#include "pear_keystore.h"
#include "log/pear_log.h"
#include "utils/pear_json.h"
#include "utils/pear_dump.h"

#define BUF_SIZE 1024

int pr_set_keystore(pr_key_t *key, char *path)
{
    size_t n   = 0;
    size_t len = 0;
    FILE  *fp  = NULL;

    char buf[BUF_SIZE]         = {0x00};
    char key_buf[BUF_SIZE]     = {0x00};
    char addr_buf[BUF_SIZE]    = {0x00};
    char temp_buf[BUF_SIZE]    = {0x00};
    char privkey_buf[BUF_SIZE] = {0x00};

    fp = fopen(path, "wb");
    if (fp == NULL)
    {
        PEAR_LOG("Unable to open file!\n");
        return -1;
    }

    pr_hash160((char *)key->pubkey, sizeof(key->pubkey), addr_buf);
    sprintf(buf, "{"
                    "\"address\": \"%s\","
                    "\"pub_key\": {" 
                        "\"type\": \"%s\","
                        "\"pub\": \"%s\"},"
                    "\"priv_key\": {"
                        "\"type\": \"%s\","
                        "\"priv\": \"%s\"}"
                 "}",
                 pr_hex_encode(temp_buf, addr_buf, strlen(addr_buf)),
                 "ecc",
                 pr_hex_encode(key_buf, (unsigned char *)key->pubkey, sizeof(pr_pubkey_t)),
                 "ecc",
                 pr_hex_encode(privkey_buf, (unsigned char *)key->privkey, sizeof(pr_privkey_t)));

    len = strlen(buf);

    while (len > 0)
    {
        if ((n = fwrite(buf, 1, len, fp)) < 0)
        {
            fclose(fp);
            return -1;
        }
        len -= n;
    }

    fclose(fp);
    return 0;
}

pr_key_t *pr_get_keystore(char *path)
{
    char buf[BUF_SIZE] = {0x00};
    pr_key_t *key = NULL;

    key = (pr_key_t *) malloc(sizeof(pr_key_t));
    if (key == NULL)
    {
        return NULL;
    }

    if (pr_json_get_string_file(path, "pub", buf) < 0)
    {
        PEAR_LOG("key file error\n");
        free(key);
        return NULL;
    }

    pr_hex_decode((unsigned char *)key->pubkey, buf, strlen(buf));
    //PEAR_LOG("\npub_key dump: %s\n", pr_hex_encode(buf, (unsigned char *)key->pubkey, sizeof(pr_pubkey_t)));

    if (pr_json_get_string_file(path, "priv", buf) < 0)
    {
        PEAR_LOG("key file error\n");
        free(key);
        return NULL;
    }

    pr_hex_decode((unsigned char *)&(key->privkey), buf, strlen(buf));

    PEAR_LOG("\npriv_buf: %s\n", buf);

    return key;
}


